package com.sakuraio.nextj.core.protocol;

import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import com.sakuraio.nextj.core.protocol.serializer.LongToIntSerializer;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Getter;
import lombok.Setter;

import java.io.Serializable;
import java.util.List;
import java.util.function.Consumer;

/**
 * <p>PageResultVO</p>
 *
 * @author nekoimi 2022/10/18
 */
@Setter
@Getter
@Schema(description = "分页数据结构")
public class PageResult<T> implements Serializable {
    @Schema(description = "总条数")
    @JsonSerialize(using = LongToIntSerializer.class)
    private Long total;

    @Schema(description = "当前页数")
    @JsonSerialize(using = LongToIntSerializer.class)
    private Long page;

    @Schema(description = "每页显示数量")
    @JsonSerialize(using = LongToIntSerializer.class)
    private Long pageSize;

    @Schema(description = "最后一页页码")
    @JsonSerialize(using = LongToIntSerializer.class)
    private Long lastPage;

    @Schema(description = "数据列表")
    private List<T> list;

    @Schema(description = "是否有下一页")
    private boolean hasNext = true;

    public PageResult() {
    }

    public PageResult(Long total, Long page, Long pageSize, Long lastPage, List<T> list) {
        this.total = total;
        this.page = page;
        this.pageSize = pageSize;
        this.lastPage = lastPage;
        this.list = list;
        this.hasNext = list.size() >= pageSize.intValue();
    }

    /**
     * 消费列表
     *
     * @param consumer 处理函数
     */
    public void consumer(Consumer<List<T>> consumer) {
        consumer.accept(this.list);
    }

    /**
     * 消费列表每一项
     *
     * @param consumer 处理函数
     */
    public void consumerItem(Consumer<T> consumer) {
        this.list.forEach(consumer);
    }
}
